document.addEventListener('DOMContentLoaded', function() {
  const startBtn = document.getElementById('startBtn');
  const stopBtn = document.getElementById('stopBtn');
  const bookIdInput = document.getElementById('bookId');
  const intervalInput = document.getElementById('interval');
  const logElem = document.getElementById('log');
  const statusElem = document.getElementById('status');
  
  // 更新进度条
  function updateProgressBar(progress) {
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    progressBar.style.width = `${progress}%`;
    progressText.textContent = `${progress}%`;
  }

  // 监听来自content script的消息
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'updateProgress') {
      updateProgressBar(message.progress);
      if (message.progress === 100) {
        appendLog('采集任务已完成');
        // 更新按钮状态
        startBtn.disabled = false;
        stopBtn.disabled = true;
        bookIdInput.disabled = false;
        intervalInput.disabled = false;
        // 更新状态
        statusElem.textContent = '未开始';
      }
    } else if (message.type === 'log') {
      appendLog(message.content);
    } else if (message.type === 'logUpdated') {
      logElem.innerHTML = message.log;
      logElem.scrollTop = logElem.scrollHeight;
    }
  });
  
  // 自动识别当前页面URL中的书籍ID
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    const url = tabs[0].url;
    const ebookMatch = url.match(/\/ebook\/(\d+)/);
    if (ebookMatch && ebookMatch[1]) {
      bookIdInput.value = ebookMatch[1];
      appendLog(`已自动识别书籍ID: ${ebookMatch[1]}`);
    }
  });
  
  // 加载状态
  async function loadStatus() {
    const result = await chrome.storage.local.get('collectionStatus');
    const status = result.collectionStatus || {
      isCollecting: false,
      bookId: '',
      interval: 10000
    };

    // 更新UI
    if (status.isCollecting) {
      statusElem.textContent = '正在采集';
      startBtn.disabled = true;
      stopBtn.disabled = false;
      bookIdInput.disabled = true;
      intervalInput.disabled = true;
      updateProgressBar(0);
    } else {
      statusElem.textContent = '未开始';
      startBtn.disabled = false;
      stopBtn.disabled = true;
      bookIdInput.disabled = false;
      intervalInput.disabled = false;
      updateProgressBar(0);
    }
  }

  // 监听状态变化
  chrome.storage.onChanged.addListener((changes, namespace) => {
    if (namespace === 'local' && changes.collectionStatus) {
      loadStatus();
    }
  });

  // 初始化状态
  loadStatus();
  
  // 设置默认间隔时间为5秒
  intervalInput.value = 5; // 默认5秒
  
  // 开始采集
  startBtn.addEventListener('click', function() {
    const bookId = bookIdInput.value.trim();
    const interval = parseInt(intervalInput.value);
    
    if (!bookId) {
      appendLog('错误: 请输入书籍ID');
      return;
    }
    
    if (isNaN(interval) || interval < 5) {
      appendLog('错误: 采集间隔不能小于5秒');
      return;
    }
    
    // 检查当前标签页
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      const currentTab = tabs[0];
      appendLog('当前页面: ' + currentTab.url);
      
      // 发送消息给content script
      chrome.tabs.sendMessage(currentTab.id, {
        action: 'start',
        bookId: bookId,
        interval: interval
      }, response => {
        if (chrome.runtime.lastError) {
          appendLog('错误: ' + chrome.runtime.lastError.message);
          return;
        }
        
        if (response && response.status === 'started') {
          appendLog('内容脚本已确认开始采集');
          startBtn.disabled = true;
          stopBtn.disabled = false;
          bookIdInput.disabled = true;
          intervalInput.disabled = true;
          statusElem.textContent = '采集中...';
          updateProgressBar(0);
        }
      });
    });
  });
  
  // 停止采集
  stopBtn.addEventListener('click', function() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {action: 'stop'}, response => {
        if (chrome.runtime.lastError) {
          appendLog('错误: ' + chrome.runtime.lastError.message);
          return;
        }
        
        if (response && response.status === 'stopped') {
          appendLog('采集已停止');
          startBtn.disabled = false;
          stopBtn.disabled = true;
          bookIdInput.disabled = false;
          intervalInput.disabled = false;
          statusElem.textContent = '未开始';
          updateProgressBar(0);
        }
      });
    });
  });
  
  function appendLog(message) {
    const now = new Date();
    const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
    logElem.innerHTML += `[${timeStr}] ${message}\n`;
    logElem.scrollTop = logElem.scrollHeight;
  }

  // 加载已保存的日志
  chrome.storage.local.get('log', (data) => {
    if (data.log) {
      logElem.innerHTML = data.log;
      logElem.scrollTop = logElem.scrollHeight;
    }
  });

  // 监听storage变化，更新文件路径显示
  chrome.storage.onChanged.addListener((changes, namespace) => {
    if (namespace === 'local') {
      if (changes.outputPath) {
        const filePathElem = document.getElementById('filePath');
        if (filePathElem) {
          filePathElem.textContent = changes.outputPath.newValue;
        }
      }
    }
  });
}); 